package com.shujia.flink.kafka;

import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Demo3Cars {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //创建kafka source
        KafkaSource<String> source = KafkaSource.<String>builder()
                .setBootstrapServers("master:9092,node1:9092,node2:9092")//kafka集群列表
                .setTopics("cars")//指定消费的topic
                .setGroupId("my-group")//指定消费者组
                // 从最早位点开始消费
                .setStartingOffsets(OffsetsInitializer.earliest())
                .setValueOnlyDeserializer(new SimpleStringSchema())//指定读取数据的格式
                .build();

        //使用kafka source
        DataStream<String> linesDS = env
                .fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source");

        //解析json格式的深故居
        DataStream<Car> cars = linesDS.map(line -> JSON.parseObject(line, Car.class));

        cars.print();

        env.execute();
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Car {
    private String car;
    private String city_code;
    private String county_code;
    private String card;
    private String camera_id;
    private String orientation;
    private Long road_id;
    private Long time;
    private Double speed;
}